package com.yyc.tool.service.impl;

import com.yyc.tool.service.ClientService;
import com.yyc.tool.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.stereotype.Service;
import org.springframework.web.HttpRequestMethodNotSupportedException;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class TokenServiceImpl implements TokenService {

    private ClientService clientService;
    private PasswordEncoder passwordEncoder;
    private TokenEndpoint tokenEndpoint;

    @Autowired
    public void setTokenEndpoint(TokenEndpoint tokenEndpoint) {
        this.tokenEndpoint = tokenEndpoint;
    }

    @Autowired
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Autowired
    public void setClientService(ClientService clientService) {
        this.clientService = clientService;
    }

    @Override
    public OAuth2AccessToken getAppToken(String clientId, String clientSecret, String scope) throws HttpRequestMethodNotSupportedException {
        ClientDetails clientDetails = clientService.loadClientByClientId(clientId);
        if (!passwordEncoder.matches(clientSecret, clientDetails.getClientSecret())) {
           log.info("权限校验失败");
        }
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(clientId, clientSecret, clientDetails.getAuthorities());
        Map<String, String> params = new HashMap<>();
        params.put(OAuth2Utils.CLIENT_ID, clientId);
        params.put("client_secret", clientSecret);
        params.put(OAuth2Utils.SCOPE, scope);
        params.put(OAuth2Utils.GRANT_TYPE, "client_credentials");
        ResponseEntity<OAuth2AccessToken> entity = tokenEndpoint.postAccessToken(authentication, params);
        return entity.getBody();
    }
}
